import hashlib
import json
import os
import shutil
import subprocess
import zipfile
from datetime import datetime, timezone, timedelta
from urllib.parse import urlparse

import lokalise
import requests

from runJenkins import server

TOKEN = 'b602ae315e398faac005abc969a8dfff10a826af'
ANDROID_PROJECT_ID = '8483564464a3b46094c650.87849900'
client = lokalise.Client(TOKEN)
project = client.project(ANDROID_PROJECT_ID)
zipFolder = "zips"
languages = ["zh_TW", "es"]

if not os.path.exists(zipFolder):
    os.makedirs(zipFolder)

import jenkins

BASE_URL = 'http://43.139.139.14:8080/'
USERNAME = 'admin'
PASSWORD = 'Ask@123'
PROJECT_NAME = "rockflow-android"
BOT_URL = "https://open.feishu.cn/open-apis/bot/v2/hook/b758c0f3-1e62-436c-b4fb-15e7d251e016"

server = jenkins.Jenkins(BASE_URL, username=USERNAME, password=PASSWORD)

# 设置本地代理地址和端口
proxy_address = 'http://127.0.0.1:7890'  # Tor 默认端口


def calculate_md5(data):
    md5 = hashlib.md5()
    md5.update(data.encode('utf-8'))
    return md5.hexdigest()


def delete_folder(folder_path):
    try:
        # 删除文件夹以及其内部的所有文件和子文件夹
        shutil.rmtree(folder_path)
        print(f"成功删除文件夹 '{folder_path}' 及其所有内容。")
    except Exception as e:
        print(f"删除文件夹 '{folder_path}' 失败：{e}")


def unzip_file(zip_file, extract_to):
    # 检查目标文件夹是否存在，不存在则创建
    if not os.path.exists(extract_to):
        os.makedirs(extract_to)
    else:
        print(f"警告：目标文件夹 '{extract_to}' 已存在，将覆盖已存在的文件。")

    # 打开zip文件
    with zipfile.ZipFile(zip_file, 'r') as zip_ref:
        # 解压所有文件到目标文件夹
        for file in zip_ref.namelist():
            file_path = os.path.join(extract_to, file)
            if file.endswith('/'):  # 文件名以斜杠结尾，表示目录
                # 创建目录
                os.makedirs(file_path, exist_ok=True)
            else:
                # 创建父目录
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                # 写入文件
                with open(file_path, 'wb') as f:
                    f.write(zip_ref.read(file))

    print(f"成功解压文件 '{zip_file}' 到 '{extract_to}' 文件夹中。")


def downloadFile():
    response = client.download_files(ANDROID_PROJECT_ID, {
        "format": "xml",
        "original_filenames": False,
        "replace_breaks": True,
        "filter_langs": languages,
        "export_sort": "first_added",
        "indentation": "4sp",
        "bundle_structure": "values-%LANG_ISO%/strings.%FORMAT%"
    })
    url = response['bundle_url']
    md5_hash = calculate_md5(url)
    url_parsed = urlparse(url)
    file_extension = os.path.splitext(url_parsed.path)[1]
    filename = md5_hash + file_extension
    zipFile = os.path.join(zipFolder, filename)
    # 设置环境变量
    os.environ['http_proxy'] = proxy_address
    os.environ['https_proxy'] = proxy_address
    response = requests.get(url, verify=False)
    if response.status_code == 200:
        with open(zipFile, 'wb') as f:
            f.write(response.content)
        print("文件下载成功")
    else:
        print("文件下载失败")
    print(url)
    unzip_file(zipFile, "./app/src/main/res/")
    delete_folder(zipFolder)


def run_git_command(command):
    result = subprocess.run(
        command.split(),  # 将命令拆分为参数列表
        stdout=subprocess.PIPE,  # 捕获标准输出
        stderr=subprocess.PIPE,  # 捕获标准错误
        text=True  # 将输出解码为文本
    )
    if result.returncode == 0:
        return result.stdout.strip()  # 返回命令输出，去除首尾空白
    else:
        print("Error:", result.stderr)
        return None


def buildApk(buildParams, notify):
    gitBranch = "origin/" + run_git_command("git rev-parse --abbrev-ref HEAD")
    region = "Domestic"
    env = "Dev"
    package = "Debug"
    if buildParams[0] == "a":
        region = "Aboard"
    if buildParams[1] == "p":
        region = "Product"
    if buildParams[1] == "r":
        region = "Release"
    parameters = {
        "branch": gitBranch,
        "packageType": "assemble",
        "region": region,
        "env": env,
        "package": package,
        "resultAction": "notify",
        "resultContent": notify
    }
    print(gitBranch + " | " + region + env + package)
    last_build_number = server.get_job_info(PROJECT_NAME)['lastCompletedBuild']['number']
    print(last_build_number)
    server.build_job(PROJECT_NAME, parameters)
    buildNumber = str(last_build_number + 1)
    print("buildNumber: " + buildNumber)
    return buildNumber


def postFeishu(branch, buildNumber):
    card = json.dumps({
        "elements": [
            {
                "tag": "markdown",
                "content": "<at email=lijinzong@flowcapai.com></at> Android翻译已更新并启动打包。\n**分支**:" + branch,
                "text_align": "left"
            },
            {
                "tag": "hr"
            },
            {
                "tag": "action",
                "actions": [
                    {
                        "tag": "button",
                        "text": {
                            "tag": "plain_text",
                            "content": "去Jenkins"
                        },
                        "type": "primary",
                        "multi_url": {
                            "url": "http://43.139.139.14:8080/job/rockflow-android/%s/" % buildNumber,
                            "pc_url": "",
                            "android_url": "",
                            "ios_url": ""
                        }
                    }
                ]
            },
            {
                "tag": "note",
                "elements": [
                    {
                        "tag": "img",
                        "img_key": "img_v3_029h_2ed9564c-e701-47d9-b0d6-1b13317ce26g",
                        "alt": {
                            "tag": "plain_text",
                            "content": ""
                        }
                    },
                    {
                        "tag": "plain_text",
                        "content": "workflow"
                    }
                ]
            }
        ],
        "header": {
            "template": "green",
            "title": {
                "content": "Android翻译已更新",
                "tag": "plain_text"
            }
        }

    })
    headers = {
        'Content-Type': 'application/json'
    }
    body = json.dumps({"msg_type": "interactive", "card": card})
    headers = {"Content-Type": "application/json"}
    requests.post(url=BOT_URL, data=body, headers=headers)


if __name__ == '__main__':
    # downloadFile()
    gitStatusResult = run_git_command("git status -s")
    gitStatusResultLines = gitStatusResult.split("\n")
    needAdd = False
    for line in gitStatusResultLines:
        if "res/values-es/strings.xml" in line:
            needAdd = True
            run_git_command("git add app/src/main/res/values-es/strings.xml")
        elif "res/values-zh-rTW/strings.xml" in line:
            needAdd = True
            run_git_command("git add app/src/main/res/values-zh-rTW/strings.xml")

    if needAdd:
        print("has new add")
        # 获取当前UTC时间
        utc_now = datetime.utcnow()
        # 设置时区为东八区
        cst_timezone = timezone(timedelta(hours=8))
        beijing_time = utc_now.replace(tzinfo=timezone.utc).astimezone(cst_timezone)
        gitCommitStr = "替换繁体和西班牙语翻译:" + str(beijing_time)
        run_git_command("git commit -m " + gitCommitStr.replace(" ", "") + "")
        run_git_command("git push")
        print("push finish")
        gitBranch = "origin/" + run_git_command("git rev-parse --abbrev-ref HEAD")
        buildNumber = buildApk("ddd", gitCommitStr)
        postFeishu(gitBranch, buildNumber)

    else:
        print("no new added")
